<template>
<!-- pages/auth/auth.wxml -->
<button type="primary" :plain="true" open-type="getUserInfo" @getuserinfo="handleGetUserInfo">
    获取授权
</button>
</template>

<script>
// pages/auth/auth.js
// 引入用来发送请求的方法 一定要把路径补全
import { request } from "../../request/index.js";
import regeneratorRuntime from "../../lib/runtime/runtime";
import { login } from "../../utils/asyncWx.js";

export default {
  data() {
    return {};
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  methods: {
    // 获取用户信息
    async handleGetUserInfo(e) {
      try {
        // console.log(e);
        // 1. 获取用户信息
        const {
          encryptedData,
          rawData,
          iv,
          signature
        } = e.detail; // 2. 获取小程序登录成功后的code

        const {
          code
        } = await login(); // console.log(code);

        const loginParams = {
          encryptedData,
          rawData,
          iv,
          signature,
          code
        }; // 3. 发送请求 获取用户的token

        const {
          token
        } = await request({
          url: "/users/wxlogin",
          data: loginParams,
          method: "post"
        }); // console.log(res);
        // 4. 把token存入缓存中 同时跳转回上一个页面

        wx.setStorageSync("token", token);
        wx.navigateBack({
          delta: 1
        });
      } catch (error) {
        console.log(error);
      }
    }

  }
};
</script>
<style>
@import "./auth.css";
</style>